﻿using System.Collections.Generic;
using System.Linq;
using Domain;
using Domain.Entities;
using BusinessLogic.Interfaces;
using System.Data.Entity;
using System;
using System.Linq.Expressions;

namespace BusinessLogic.Implementations
{
    // реализация интерфейса
    public class EFUsersRepository : IUsersRepository
    {

        private DomainContext context;
        public EFUsersRepository(DomainContext context)
        {
            this.context = context;
        }

        public IEnumerable<User> GetList(Expression<Func<User, bool>> filter)
        {
            return context.Users.Where(filter);
        }

        //public IEnumerable<User> GetProfileByName(string Name)
        //{
        //    return GetList(x => x.FirstName == Name);
        //}

        public IEnumerable<User> GetUsersAll()
        {
            return context.Users;
        }

        public User GetUserById(int id)
        {
            return context.Users.FirstOrDefault(x => x.ID == id);
        }

        public User GetUserByName(string userName)
        {
            return context.Users.FirstOrDefault(x => x.Name == userName);
        }

        public void CreateUser(string userName, string pas,
            int profileId, int roleId)
        {
           
            User us = new User
            {
                Name = userName,
                Password = pas,
                ProfileID=profileId,
                RoleID=roleId
            };
            SaveUser(us);
        }

        public bool ValidateUser(string userName, string password)
        {
            User us = context.Users.FirstOrDefault(x => x.Name == userName);
            if (us != null && us.Password == password)
                return true;
            return false;
        }

        public void SaveUser(User user)
        {
            try
            {
                if (user.ID == 0) // если не существует id, добавляем нового пользователя
                    context.Users.Add(user);
                else // иначе редактируем
                    context.Entry(user).State = EntityState.Modified;
                context.SaveChanges();
            }
            catch (Exception)
            { }
        }


        public void DeleteUser(User user)
        {
            context.Users.Remove(user);
            context.SaveChanges();
        }

        public IEnumerable<User> GetUsers(string userName, string pas)
        {
            return context.Users.Where(x => (x.Name == userName) && (x.Password == pas));
        }

        public User GetUser(string userName, string pas)
        {
            return context.Users.FirstOrDefault(x => (x.Name == userName) && (x.Password == pas));
        }



        public Profile GetListProfiles(User us)
        {
            throw new NotImplementedException();
        }
    }
}
